package com.ad.pet.app.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ad.pet.App;
import com.ad.pet.MainActivity;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.login.fragment.AccountLoginFragment;
import com.ad.pet.app.login.fragment.EmailRegistFragment;
import com.ad.pet.common.data.injector.HasComponent;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.Events;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.User;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登录注册
 * Created by SEELE on 2018/3/20.
 */

public class MobileInputActivity extends AppToolbarActivity implements HasComponent<LoginComponet> ,MobileInputContract.View{

    @Inject
    MobileInputPresenter mInputPresenter;

    LoginComponet mCircularComponent;

    @BindView(R.id.tv_login)
    TextView mTvLogin;

    @BindView(R.id.tv_private)
    TextView tv_private;

    @BindView(R.id.tv_regist)
    TextView mTvRegist;

    @BindView(R.id.tv_private2)
    TextView tv_private2;

    @BindView(R.id.viewpager)
    ViewPager mViewPager;

    @BindView(R.id.ic_wexin)
    ImageView mIvWeixin;

//    private String mThirdType;
    private String mThirdValue;
    private String mThirdName;
    private String mUserUrl;
    private String mUniqueID="";
    private String mOpenId;

    private UMShareAPI mMShareAPI;

    Fragment mLoginFragment;
    public Fragment mRegistFragment;

    private boolean isLeft =true;//判断是注册还是登陆，true登陆，false注册

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mStatusLayoutManager.showContent();

    }

    @Override
    protected void initViews() {
        mMShareAPI = UMShareAPI.get(mActivity);
        mInputPresenter.onCreate(this);
        mLoginFragment = new AccountLoginFragment();
        mRegistFragment = new EmailRegistFragment();

        int type = getIntent().getIntExtra("type",0);

        final List<Fragment> fragments = new ArrayList<>();
        fragments.add(mRegistFragment);
        fragments.add(mLoginFragment);


        mViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        });


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setTopView(position == 0);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        setTopView(!isLeft);
        switchContent(!isLeft);

    }

    public void switchContent(boolean isLeft) {

        if (isLeft) {
            mViewPager.setCurrentItem(0);
        } else {
            mViewPager.setCurrentItem(1);
        }

    }

    @OnClick({R.id.tv_login, R.id.tv_regist})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                isLeft = false;
                switchContent(isLeft);
                break;
            case R.id.tv_regist:

                isLeft = true;
                switchContent(isLeft);
                break;
        }
    }

    public void setTopView(boolean isLeft) {
        if (isLeft) {

            mTvLogin.setTextColor(mActivity.getResources().getColor(R.color.textGrayColor));
            mTvLogin.setTextSize(13);
            mTvRegist.setTextColor(mActivity.getResources().getColor(R.color.black));
            mTvRegist.setTextSize(16);

        } else {

            mTvLogin.setTextColor(mActivity.getResources().getColor(R.color.black));
            mTvLogin.setTextSize(16);
            mTvRegist.setTextColor(mActivity.getResources().getColor(R.color.textGrayColor));
            mTvRegist.setTextSize(13);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvents() {
        tv_private2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goCommonWebView(mActivity,"",getString(R.string.ip_host)+"/index.html#/service/PrivacyPolicy");
            }
        });
        tv_private.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.goCommonWebView(mActivity,"",getString(R.string.ip_host)+"/index.html#/service/ServicesAgreement");
            }
        });
        mIvWeixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mMShareAPI.getPlatformInfo(mActivity, SHARE_MEDIA.WEIXIN, authListener);
            }
        });
    }

//    @Override
//    protected void setContentViewBefore() {
//        super.setContentViewBefore();
//        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);
//
//    }

    @Override
    public void initInject() {
        mCircularComponent = DaggerLoginComponet.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build();
        mCircularComponent.inject(this);
    }


    @Override
    protected int contentLayout() {
        return R.layout.activity_mobile_input;
    }

    @Override
    protected void clickRetry(View v) {

    }


    @Override
    protected BasePresenter getPresenter() {
        return null;
    }


    @Override
    protected boolean isStatusBarTransparent() {
        return true;
    }


    @Override
    protected void onDestroy() {
        UMShareAPI.get(this).release();
        super.onDestroy();


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }


    @Override
    public LoginComponet getComponent() {
        return mCircularComponent;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

        if (data == null)
            return;
        switch (requestCode) {
            case MainActivity.REQUEST_GO_MALL:
                setResult(RESULT_OK, data);
                finish();
                break;

        }
    }



    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }
        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            mUniqueID = data.get("uid");
            mThirdName = data.get("name");
            mUserUrl = data.get("iconurl");
            mThirdValue = data.get("openid");
//            mUniqueID=data.get("");

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mInputPresenter.checkBindThird(mThirdValue);
                        }
                    }).start();





        }
        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(mActivity, "微信登录失败", Toast.LENGTH_LONG).show();
        }
        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(mActivity, "取消登录", Toast.LENGTH_LONG).show();
        }


    };


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void checkPhoneSuccess(int isRegist) {

    }

    @Override
    public void checkBindThirdSuccess(User user) {
        SpUtil.getInstance().putString(Constant.USER_ID,user.getUser_name());
        SpUtil.getInstance().putString(Constant.ACCESS_TOKEN,user.getToken());
        App.username = user.getUser_name();
        App.phone = user.getUser_tel();
        ToastUtil.getToastUtil().showShort(getString(R.string.login_success));
        RxBus.getDefault().post(new Events.AddCarts());
        RxBus.getDefault().post("set_message_number_success");
        finish();
    }

    @Override
    public void checkBindUnBind() {
        Navigation.goThirdBind(mActivity,mThirdValue,mUserUrl,mThirdName,mUniqueID);
    }

    @Override
    public void thirdLoginSuccess(User user) {

    }
}